package com.kun.companion.core.thread;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/2/7 10:49
 **/
public class NamedThreadFactory implements ThreadFactory {
    private final Logger log = LoggerFactory.getLogger(NamedThreadFactory.class);
    /**
     * 线程数
     */
    protected final AtomicInteger THREAD_NUM = new AtomicInteger(1);
    /**
     * 线程名称前缀
     */
    protected final String THREAD_NAME_PREFIX;
    /**
     * 是否开启守护线程
     */
    protected final boolean ENABLE_DAEMON;
    /**
     * 优先级
     */
    protected final int PRIORITY;
    /**
     * 线程组
     */
    protected final ThreadGroup THREAD_GROUP;

    public NamedThreadFactory() {
        this("name");
    }

    public NamedThreadFactory(String prefix) {
        this(prefix, Thread.NORM_PRIORITY, false);
    }

    public NamedThreadFactory(String prefix, int priority, boolean daemon) {
        THREAD_NAME_PREFIX = prefix + "-thread-";
        PRIORITY = priority;
        ENABLE_DAEMON = daemon;
        THREAD_GROUP = Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(@NotNull Runnable runnable) {
        String name = THREAD_NAME_PREFIX + THREAD_NUM.getAndIncrement();
        Thread thread = new Thread(THREAD_GROUP, runnable, name, 0);
        thread.setDaemon(ENABLE_DAEMON);
        thread.setPriority(PRIORITY);
        // 全局异常捕获（防止线程静默失败）
        thread.setUncaughtExceptionHandler((t, ex) ->
                log.error("线程[{}]发生未捕获异常: {}", t.getName(), ex.getMessage(), ex)
        );
        return thread;
    }

    public ThreadGroup getThreadGroup() {
        return THREAD_GROUP;
    }

    public int getPriority() {
        return PRIORITY;
    }

}
